package com.rc.saas.tenant.shiro;

import com.rc.saas.tenant.common.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

/**
 * 扩展密码校验
 */
public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {
    private static Logger logger = LogManager.getLogger(CustomCredentialsMatcher.class);

    /**
     * 密码比对
     *
     * @param authcToken
     * @param info
     * @return
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) {
        String username = getUsername(authcToken);
        String inputPassword = getInputPassword(authcToken);
        String credentials = getUserPassword(info);

        //密码以用户名称作为salt
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(inputPassword) && StringUtils.isNotBlank(credentials)) {
            return MD5Utils.encrypt(username, inputPassword).equals(credentials);
        }

        return false;
    }

    private String getUsername(AuthenticationToken authcToken) {
        String username = String.valueOf(authcToken.getPrincipal());
        return username;
    }

    private String getInputPassword(AuthenticationToken authcToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        return String.valueOf(token.getPassword());
    }

    private String getUserPassword(AuthenticationInfo info) {
        //从存储的info中提取密文
        String credentials = String.valueOf(getCredentials(info));
        return credentials;
    }

}
